package com.jb.web.bean.custom.renderer;

import com.jb.web.bean.custom.Rater;
import com.jb.web.context.WebContext;
import com.jb.web.renderer.DefaultRenderer;

import com.jb.faces.component.UIComponent;


public class RaterRenderer extends DefaultRenderer {
    /**
     * @param pCtx
     * @param itemToRender
     * @return
     */
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        Rater rater = (Rater) itemToRender;

        StringBuffer html = new StringBuffer();
        html.append("<div ").append(addTagProperty("style", rater.getStyle(pCtx), null))
        .append(addTagProperty("class", rater.getStyleClass(), "jbRater"))
        .append(getEditScript(pCtx, rater)).append(" >");

        html.append(renderChildren(pCtx, itemToRender))
            .append("</div>");

        return html;
    }
    
    public StringBuffer renderChildren(WebContext pCtx, UIComponent itemToRender) {
        Rater rater = (Rater) itemToRender;
        Float rate = new Float(rater.getCurrentRate());
        String cid = rater.getClientId();
        String defaultValue = rater.getDefaultValue();
        if(defaultValue!=null && defaultValue.length()>0)
        {
          try
          {
            rate = new Float(evaluate(pCtx, rater,defaultValue));
          }catch(Exception e)
          {
            pCtx.addErrorMessage(this, "Failed to evaluate "+defaultValue);
            rate = new Float(0);
          }
        }
        StringBuffer html = new StringBuffer();
        if(pCtx.isRunTime())
        {
          html.append("<ul class=\"star-rating\" >")
            .append("<li class=\"current-rating\" style=\"width:"+rate.floatValue()*25+"px;\">Currently 4/5 Stars.</li>")
            .append("<li><a href=\"#\" onClick=\"JB.setRate('"+cid+"',1);\" title=\"1 star out of 5\" class=\"one-star\">1</a></li>")
            .append("<li><a href=\"#\" onClick=\"JB.setRate('"+cid+"',2);\" title=\"2 stars out of 5\" class=\"two-stars\">2</a></li>")
            .append("<li><a href=\"#\" onClick=\"JB.setRate('"+cid+"',3);\" title=\"3 stars out of 5\" class=\"three-stars\">3</a></li>")
            .append("<li><a href=\"#\" onClick=\"JB.setRate('"+cid+"',4);\" title=\"4 stars out of 5\" class=\"four-stars\">4</a></li>")
            .append("<li><a href=\"#\" onClick=\"JB.setRate('"+cid+"',5);\" title=\"5 stars out of 5\" class=\"five-stars\">5</a></li>").append("</ul>")
            ;
        }
        return html;
    }}
